<template>
  <view class="ui-price ui-txt">
    <!-- 货币符号 -->
    <text class="price-symbol" v-if="needSymbol">￥</text>
    <!-- 金额 -->
    <text class="price-big" :style="bigStyle">{{ bigPrice }}</text>
    <!-- 小数点 -->
    <text class="price-point" v-if="decimalDigits > 0">.</text>
    <!-- 小数位数据 -->
    <text class="price-small" v-if="decimalDigits > 0">{{ smallPrice }}</text>
  </view>
</template>
<script>
export default {
  name: "uiPrice",
  props: {
    // 金额
    price: {
      type: [Number, String],
      default: 0
    },
    // 是否需要显示货币符号
    needSymbol: {
      type: Boolean,
      default: true
    },
    // 小数位个数
    decimalDigits: {
      type: [Number, String],
      default: 2
    },
    // 是否使用千分位隔断
    thousands: {
      type: Boolean,
      default: false
    },
    color: {
      type: String,
      default: "#f54305"
    },
    size: {
      type: [Number, String],
      default: 32
    }
  },
  data() {
    return {
      bigPrice: "",
      smallPrice: ""
    };
  },
  computed: {
    bigStyle() {
      return `color:${this.color};font-size:${this.px(this.size)}`;
    }
  },
  watch: {
    price: {
      handler() {
        this.formatToHump(this.price);
      }
    }
  },
  created() {
    this.formatToHump(this.price);
  },
  methods: {
    //判断是否为小数点
    checkPoint(num) {
      return String(num).indexOf(".") > 0;
    },

    //将数字转换成驼峰形式
    formatToHump(num) {
      let self = this;
      num = String(num).replace("￥", "");
      let numArray = String(num).split(".");
      // 如果存在小数位
      if (self.checkPoint(num)) {
        this.bigPrice = self.formatThousands(numArray[0]);
        this.smallPrice = self.formatDecimal(numArray[1]);
      } else {
        this.bigPrice = self.formatThousands(numArray[0]);
        this.smallPrice = self.formatDecimal(0);
      }
    },

    //根据小数位数格式化小数部分
    formatDecimal(decimalNum) {
      let self = this;
      let decimalDigits = self.decimalDigits;
      let result = "0." + String(decimalNum);
      let resultFixed = (result / 1).toFixed(decimalDigits);
      return String(resultFixed).substring(2, resultFixed.length);
    },
    //千分位显示
    formatThousands(num) {
      let self = this;
      let result = "";
      if (self.thousands) {
        return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
      } else {
        return num;
      }
    },
    px(num) {
      return uni.upx2px(num) + "px";
    }
  }
};
</script>

<style lang="scss">
.ui-price {
  font-size: $font-size-small;
  display: inline;
  .price-symbol {
    font-size: $font-size-small;
  }
  .price-big {
    font-size: $font-size-large;
    color: $brand-primary;
  }
  .price-small {
    font-size: $font-size-small;
  }
}
</style>
